package com.example.demo.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
 * @version: V0.3
 * @author: 郑皓杰 吴嘉鑫
 * @className: FileUtils
 * @packageName: com.example.demo.utils
 * @description: 这是上传读取文件的工具类
 * @data: 2021-07-16
 **/
public class FileUtils {
	
	
	/**
	* @author:吴嘉鑫 郑皓杰
	* @methodsName: upload
	* @description: 上传文件
	* @param:  MultipartFile file
	* @return: APIResponse
	* @throws: IOException
	*/
	
	public static String upload(MultipartFile file,String uniqueId) throws IOException{
		String fileName = file.getOriginalFilename();
		byte[] bytes = file.getBytes();
		String key = UuidUtils.getUuid();
		File folder = new File("./filefolder/"+uniqueId+"/");
		System.out.println(folder.getAbsolutePath());	
		if(!folder.exists()) folder.mkdirs();
		File newFile = new File(folder,key+fileName);
		OutputStream out = new FileOutputStream(newFile);
		out.write(bytes);
		out.flush();
		out.close();
		return "上传成功";
		
		/*
		String filePath = "C:\\Users\\SimpleChris\\A01\\five-twist-a01\\AOI_BACK\\file\\" + key + "-" + fileName;
		File dest = new File(filePath);
		System.out.println(dest.getAbsolutePath());
		file.transferTo(dest);
		return APIResponse.success("成功传入");*/	
	}
	
	
	/**
	* @author:吴嘉鑫 郑皓杰
	* @methodsName: download
	* @description: 下载文件
	* @param:  MultipartFile file
	* @return: APIResponse
	* @throws: IOException
	*/
	
	public static void download(String path,HttpServletResponse response) throws IOException{
		File file=new File(path);
		FileInputStream fis=new FileInputStream(file);
		byte[] buffer=new byte[fis.available()];
		fis.read(buffer);
		fis.close();
		
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
		response.addHeader("Content-Length",""+file.length());
		OutputStream out=new BufferedOutputStream(response.getOutputStream());
		response.setContentType("applicaation/octet-stream");
		out.write(buffer);
		out.flush();
		out.close();
	}
	
	
	

}
